package com.sunspring.jbug.controller;

import com.sunspring.jbug.bean.UserInfo;
import com.sunspring.jbug.common.SimpleResponse;
import com.sunspring.jbug.common.constant.HttpConstant;
import com.sunspring.jbug.common.exception.JbugException;
import com.sunspring.jbug.service.EmailService;
import com.sunspring.jbug.service.UserService;
import com.sunspring.jbug.util.Md5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wulei
 * @date 2019-02-27
 **/
@RestController
@Api(value = "登录和注册模块")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    /**
     * 发送邮箱注册验证码
     */
    @PostMapping("/jbug/reg/verificationCode")
    @ApiOperation(value = "发送邮箱注册验证码")
    public SimpleResponse jBugRegEmail(String email) {
        emailService.regSendVerificationCode(email);
        return SimpleResponse.success();
    }

    /**
     * 邮箱注册
     * @param userInfo userInfo
     * @param code 验证码
     */
    @PostMapping("/jbug/reg")
    @ApiOperation("输入验证码后的注册")
    public SimpleResponse reg(UserInfo userInfo,String code) {
        emailService.regByEmail(userInfo,code);
        return SimpleResponse.success();
    }

    /**
     * 前端登录
     */
    @PostMapping("/portal/login")
    @ApiOperation(value = "前端登录")
    public SimpleResponse bugLogin(HttpServletRequest request,String username, String password) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(Md5Util.md5(password));
        List<UserInfo> list = userService.getSelective(userInfo);
        if (CollectionUtils.isEmpty(list)) {
            throw new JbugException("登录失败");
        }
        userInfo = list.get(0);
        request.getSession().setAttribute(HttpConstant.SessionKey,userInfo);
        return SimpleResponse.success(list.get(0));
    }

    @RequestMapping("/test")
    public Object test(HttpServletRequest request) {
        return request.getSession().getAttribute(HttpConstant.SessionKey);
    }

    public static void main(String[] args) {
        System.out.println(Md5Util.md5("123"));
    }
}
